package com.wyx.mhl.dao;

import com.wyx.mhl.utils.JDBCUtils_Druid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 王艺锡
 * @version 1.0
 *  BasicDao,是其他Dao的父类
 */
public class BasicDao<T> {//泛型用于指定具体类型
    private QueryRunner qr = new QueryRunner();

    //开发通用的dml方法
    public int update(String sql,Object...parameters){
        Connection connection = null;

        try {
            connection = JDBCUtils_Druid.getConnection();
            int update = qr.update(connection, sql, parameters);
            return update;

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
        JDBCUtils_Druid.close(null,null,connection);
        }


    }

    //查询多行多列的方法，返回一个集合
    public List<T> queryMulti(String sql,Class<T> clazz,Object...parameters){
        Connection connection = null;

        try {
            connection = JDBCUtils_Druid.getConnection();
            return qr.query(connection, sql, new BeanListHandler<T>(clazz), parameters);

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils_Druid.close(null,null,connection);
        }


    }




    //查询单行多列的方法，返回一个Bean对象
    public T querySingle(String sql,Class<T> clazz,Object...parameters){
        Connection connection = null;

        try {
            connection = JDBCUtils_Druid.getConnection();
            return qr.query(connection, sql, new BeanHandler<T>(clazz), parameters);

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils_Druid.close(null,null,connection);
        }


    }



    //查询单行单列的方法，返回单值
    public Object queryScalar(String sql,Object...parameters){
        Connection connection = null;

        try {
            connection = JDBCUtils_Druid.getConnection();
            return qr.query(connection,sql,new ScalarHandler<>(),parameters);

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils_Druid.close(null,null,connection);
        }


    }


}
